<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\HttpController\adminapi\setting;

use App\HttpController\adminapi\AuthController;
use App\Model\Admin\SystemAdminModel;
use App\Services\System\Admin\SystemAdminServices;
use EasySwoole\FastCache\Cache;
use EasySwoole\Http\Message\Status;
use EasySwoole\Validate\Validate;

/**
 * Description of SystemAdmin
 *
 * @author zike
 */
class SystemAdmin extends AuthController {

    //put your code here


    protected function getValidateRule(?string $action): ?Validate {
	switch ($action) {
	    case 'login':
		$validate = new Validate();
//                $validate->addColumn('imgcode')->required();
//                $validate->addColumn('account')->required()->alphaDash();
//                $validate->addColumn('pwd')->required();
		return $validate;
		break;
	}
	return null;
    }

    /**
     * 显示管理员资源列表
     *
     * @return \think\Response
     */
    public function index() {
	$where = [
	    'status' => $this->request()->getRequestParam('status') ?? '',
	    'name' => $this->request()->getRequestParam('name') ?? ''
	];
	$ret = SystemAdminServices::getInstance()->getAdminList($where, $this->adminInfo->level + 1);
	return $this->writeJson(Status::CODE_OK, $ret, 'ok');
    }

    /**
     * 创建表单
     * @return mixed
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function create() {
	$ret = SystemAdminServices::getInstance()->createForm($this->adminInfo->level + 1);
	return $this->writeJson(Status::CODE_OK, $ret, 'ok');
    }

    /**
     * 保存管理员
     * @return mixed
     */
    public function save() {
	$data = [
	    'account' => $this->request()->getRequestParam('account') ?? '',
	    'conf_pwd' => $this->request()->getRequestParam('conf_pwd') ?? '',
	    'pwd' => $this->request()->getRequestParam('pwd') ?? '',
	    'real_name' => $this->request()->getRequestParam('real_name') ?? '',
	    'status' => $this->request()->getRequestParam('status') ?? 0,
	    'roles' => $this->request()->getRequestParam('roles') ?? [],
	];

	if (!$data['account'])
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '请输入管理员账号');
	if (!is_array($data['roles']) || !count($data['roles']))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '请选择最少一个权限');
	$data['roles'] = implode(',', $data['roles']);
	$data['level'] = $this->adminInfo['level'] + 1;
	if (!SystemAdminModel::create()->data($data, false)->save())
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '添加失败');
	return $this->writeJson(Status::CODE_OK, [], '添加成功');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit() {
	$id = intval($this->request()->getRequestParam('id'));
	if (!$id) {
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '管理员信息读取失败');
	}
	$ret = SystemAdminServices::getInstance()->updateForm($this->adminInfo->level + 1, $id);
	return $this->writeJson(Status::CODE_OK, $ret, 'ok');
    }

    /**
     * 修改管理员信息
     * @param $id
     * @return mixed
     */
    public function update() {
	$data = [
	    'account' => $this->request()->getRequestParam('account') ?? '',
	    'conf_pwd' => $this->request()->getRequestParam('conf_pwd') ?? '',
	    'pwd' => $this->request()->getRequestParam('pwd') ?? '',
	    'real_name' => $this->request()->getRequestParam('real_name') ?? '',
	    'status' => $this->request()->getRequestParam('status') ?? 0,
	    'roles' => $this->request()->getRequestParam('roles') ?? [],
	];

	$id = intval($this->request()->getRequestParam('id'));
	if (!$id || !($admin = SystemAdminModel::create()->get($id)))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '数据不存在');
	if (!$data['account'])
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '请输入管理员账号');
	if (!is_array($data['roles']) || !count($data['roles']))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '请选择最少一个权限');
	$data['roles'] = implode(',', $data['roles']);
	$data['level'] = $this->adminInfo['level'] + 1;
	if (!$admin->update($data))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '修改失败');
//	    \think\facade\Cache::clear();//todo
	return $this->writeJson(Status::CODE_OK, [], '修改成功');
    }

    /**
     * 删除管理员
     * @param $id
     * @return mixed
     */
    public function delete() {
	$id = intval($this->request()->getRequestParam('id'));
	if (!$id || !($admin = SystemAdminModel::create()->get($id)))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '数据不存在');
	if (!$admin->update(['is_del' => 1, 'status' => 0]))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '删除成功');
	return $this->writeJson(Status::CODE_OK, [], '删除成功');
    }

    /**
     * 修改状态
     * @param $id
     * @param $status
     * @return mixed
     */
    public function set_status() {
	$id = intval($this->request()->getRequestParam('id'));
	if (!$id || !($role = SystemAdminModel::create()->get($id)))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '数据不存在');

	$status = intval($this->request()->getRequestParam('status'));
	if ($role->update(['status' => $status]))
	    return $this->writeJson(Status::CODE_OK, [], ($status == 0 ? '关闭成功' : '开启成功'));
	else
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '操作失败');
    }

    /**
     * 修改当前登陆admin信息
     * @return mixed
     */
    public function update_admin() {
	$data = [
	    'pwd' => $this->request()->getRequestParam('pwd') ?? '',
	    'new_pwd' => $this->request()->getRequestParam('new_pwd') ?? '',
	    'conf_pwd' => $this->request()->getRequestParam('conf_pwd') ?? '',
	    'real_name' => $this->request()->getRequestParam('real_name') ?? '',
	    'head_pic' => $this->request()->getRequestParam('head_pic') ?? '',
	];

	if (!preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,}$/', $data['new_pwd'])) {
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '设置的密码过于简单(不小于六位包含数字字母)');
	}
	if (!$admin->update($data, ['id' => $this->adminId]))
	    return $this->writeJson(Status::CODE_BAD_REQUEST, [], '修改失败');
	return $this->writeJson(Status::CODE_OK, [], '修改成功');
    }

    /**
     * 获取当前登陆管理员的信息
     * @return mixed
     */
    public function info() {
	$this->writeJson(Status::CODE_OK, $this->adminInfo, 'ok');
    }

    /**
     * 退出登陆
     * @return mixed
     */
    public function logout() {
	$key = trim(ltrim(($this->request()->getHeader('Authori-zation')[0] ?? ''), 'Bearer'));
	Cache::getInstance()->unset(md5($key));
	$this->writeJson(Status::CODE_OK, [], 'ok');
    }

}
